<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form onsubmit="return false">
    <textarea name="massage" style="height: 300px;width: 300px" ></textarea>


    <textarea id="responseText"  style="height: 300px;width: 300px" > </textarea>
    <input type="button" value="提交内容" onclick="send(this.form.massage.value)">
    <input type="button" value="打开端口" onclick="wsopen()">
    <input type="button" value="关闭端口" onclick="wsclose()" >
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">


    <script>
        var websocket;

        function wsopen() {


            if (!('WebSocket' in window))
                alert("浏览器不支持websocket");

            if(websocket!=null){
                websocket.close();
                websocket=null;
            }


            websocket = new WebSocket("ws://127.0.0.1:10104/chrisws");



            websocket.onmessage = function (ev) {
               // alert(ev);
                setMessageInnerHTML(ev.data);
            };

            websocket.onopen = function (ev) {
                setMessageInnerHTML("链接开启。。。");
            };

            websocket.onclose = function (ev) {
                setMessageInnerHTML("链接关闭");
            };

            websocket.onerror = function (ev) {
                setMessageInnerHTML( "链接出现错误");
            };
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            if (document.getElementById('responseText').innerHTML!="")
                document.getElementById('responseText').innerHTML="\n"+ document.getElementById('responseText').innerHTML;
            document.getElementById('responseText').innerHTML = innerHTML+document.getElementById('responseText').innerHTML;
        }

        //发送消息
        function send(massage)
        {
            if (!('WebSocket' in window))
                return;
            if (websocket.readyState ==WebSocket.OPEN)
            {
                websocket.send(massage);
            }
            else
                alert("链接未开启")
        }

        //关闭连接
        function wsclose() {
            websocket.close();
        }

        wsopen();
    </script>

</form>
</body>
</html>